# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import logging

from pylons import tmpl_context as c, request, url
from pylons.i18n import lazy_ugettext as _

from sqlalchemy import desc, func

from repoze.what.plugins.pylonshq import ControllerProtector
from repoze.what.predicates import has_permission

from webhelpers.html.tags import link_to, literal

from chowa.lib.site.navigation import get_page
from chowa.lib.site.crud import FlatCrudController

from hrms.lib.base import render, Session
from hrms.model.organization import Order

log = logging.getLogger(__name__)

@ControllerProtector(has_permission('hrms.administer.orders'))
class ListController(FlatCrudController):
    __model__ = Order
    __edit_columns__ = ['type', 'number', 'approved']
    __main_heading__ = _('Orders')
    
    def index(self):
        query = Session.query(Order).filter(Order.approved > 0)
        
        years_query = query.group_by(func.year(Order.approved))
        years_query = years_query.filter(func.year(Order.approved) >= 2010)
        c.years = ['...', '199..', '200..'] + [str(order.approved.year) for order in years_query]
        c.year = request.params.get('year') or '...'
        
        if not c.year == '...':
            if '..' in c.year:
                start = c.year.replace('..', '0')
                end = c.year.replace('..', '9')
                query = query.filter(func.year(Order.approved) >= start)
                query = query.filter(func.year(Order.approved) <= end)
            else:
                query = query.filter(func.year(Order.approved) == c.year)
        query = query.order_by(Order.approved)
        c.orders = get_page(query, items_per_page=20)
        
        return render('/hrms/orders/index.html')
    
    def errors(self):
        query = Session.query(Order, func.count(Order.id).label('cnt'))
        subq = query.group_by(Order.number, func.year(Order.approved)).subquery()
        query = Session.query(subq).filter(subq.c.cnt > 1).order_by('approved desc')
        c.errors = get_page(query, items_per_page=20)
        
        duplicates = lambda order: Session.query(Order) \
                                          .filter_by(number=order.number) \
                                          .filter(func.year(Order.approved) == func.year(order.approved)).all()
        
        def message(duplicates):
            ids = [str(order.id) for order in duplicates]
            names = ['#%s (%s)' % (order.number, order.approved) for order in duplicates]
            link = link_to(', '.join(names), url(controller='orders/merge',
                                                 action='select',
                                                 ids='.'.join(ids)))
            return literal(_('Duplicate orders: %s') % link)
        
        c.message = lambda order: message(duplicates(order))
        return render('/hrms/orders/errors.html')
